﻿using Grpc.Core;
using MX.Core.Extensions;
using MX.Core.Log;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UserCenter.Console.Sdk.Core;
using UserCenter.Console.Sdk.Models;
using UserCenter.Console.Sdk.Results;
using UserCenter.Grpc;
using UserCenter.Grpc.Sdk;

namespace UserCenter.Console.Sdk
{
    public class MemberSdk : BaseSdk
    {
        public MemberSdk(long merchantId, string signKey, string host, int port) : base(merchantId, signKey, host, port)
        {
        }

        /// <summary>
        /// 注册
        /// </summary>
        /// <param name="userName"></param>
        /// <returns></returns>
        public async Task<RegisterResult> RegisterAsync(string userName)
        {
            RegisterResult result = new RegisterResult();
            if (string.IsNullOrEmpty(userName))
            {
                var grpcResult = await RequestAsync(client.PwdRegisterAsync, new PwdRegisterRequest
                {
                    UserName = userName
                });
                result.SetStatus(grpcResult);
                if (result.Success)
                {
                    result.MemberId = grpcResult.Response.MemberId;
                }
            }
            else
            {
                result.Message = "用户名不能为空";
            }
            return result;
        }


        public async Task<T> GetMemberAsync<T>(long memberId) where T : BaseMemberResult, new()
        {
            var result = new T();
            if (memberId > 0)
            {
                var grpcResult = await RequestAsync(client.GetMemberAsync, new GetMemberRequest
                {
                    MemberId = memberId
                });
                result.SetStatus(grpcResult);
                if (result.Success)
                {
                    result.MemberId = grpcResult.Response.MemberId;
                    result.AvatarUrl = grpcResult.Response.AvatarUrl;
                    result.UserName = grpcResult.Response.UserName;
                    result.Status = grpcResult.Response.LoginStatus.ToResultStatus();
                    if (!string.IsNullOrEmpty(grpcResult.Response.ExtJson))
                    {
                        try
                        {
                            JsonConvert.PopulateObject(grpcResult.Response.ExtJson, result);
                        }
                        catch (Exception ex)
                        {
                            logger.Debug(ex.ToString());
                        }
                    }

                }
            }
            else
            {
                result.Message = "用户名不能为空";
            }
            return result;
        }


        public async Task<T> GetMemberAsync<T>(string userName) where T : BaseMemberResult, new()
        {
            var result = new T();
            if (!string.IsNullOrEmpty(userName))
            {
                var grpcResult = await RequestAsync(client.GetMemberByUserNameAsync, new GetMemberByUserNameRequest
                {
                     UserName = userName
                });
                result.SetStatus(grpcResult);
                if (result.Success)
                {
                    result.MemberId = grpcResult.Response.MemberId;
                    result.AvatarUrl = grpcResult.Response.AvatarUrl;
                    result.UserName = grpcResult.Response.UserName;
                    result.Status = grpcResult.Response.LoginStatus.ToResultStatus();
                    if (!string.IsNullOrEmpty(grpcResult.Response.ExtJson))
                    {
                        try
                        {
                            JsonConvert.PopulateObject(grpcResult.Response.ExtJson, result);
                        }
                        catch (Exception ex)
                        {
                            logger.Debug(ex.ToString());
                        }
                    }

                }
            }
            else
            {
                result.Message = "用户名不能为空";
            }
            return result;
        }


        public async Task<CheckTokenResult> CheckTokenAsync(string token)
        {
            var result = new CheckTokenResult();
            if (!string.IsNullOrEmpty(token))
            {
                var grpcResult = await RequestAsync(client.CheckTokenAsync, new CheckTokenRequest
                {
                    Token = token
                });
                result.SetStatus(grpcResult);
                if (result.Success)
                {
                    if (grpcResult.Response.Success)
                    {
                        result.MemberId = grpcResult.Response.MemberId;
                    }
                    else
                    {
                        result.Success = false;
                        result.Message = "TOKEN验证失败";
                    }

                }
            }
            else
            {
                result.Message = "TOKEN不能为空";
            }
            return result;

        }

        public async Task<SetExtResult> SetExtAsync(long memberId, string jsonData)
        {
            var result = new SetExtResult();
            if (memberId > 0)
            {
                if (!string.IsNullOrEmpty(jsonData))
                {
                    var grpcResult = await RequestAsync(client.SetExtAsync, new SetExtRequest
                    {
                        MemberId = memberId,
                        JsonData = jsonData
                    });
                    result.SetStatus(grpcResult);
                    return result;
                }
                else
                {
                    result.Message = "JSON数据不能为空";
                }
            }
            else
            {
                result.Message = "用户ID不能为空";
            }
            return result;
        }

        public async Task<ParentListResult> GetParents(long memberId)
        {
            var result = new ParentListResult();
            if (memberId > 0)
            {
                var grpcResult = await RequestAsync(client.GetParentListAsync, new GetParentListRequest
                {
                    MemberId = memberId,
                });
                result.SetStatus(grpcResult);
                if (result.Success)
                {
                    result.Parents = grpcResult.Response.Layer.Select(l => new ParentLayer
                    {
                        Layer = l.Layer,
                        MemberId = l.MemberId,
                        ParentId = l.ParentId
                    }).ToList();

                }
                return result;
            }
            else
            {
                result.Message = "用户ID不能为空";
            }
            return result;
        }


        public async Task<ChildrenResult> GetChildren(long memberId)
        {
            var result = new ChildrenResult();
            if (memberId > 0)
            {
                var grpcResult = await RequestAsync(client.GetChildAsync, new GetChildRequest
                {
                    MemberId = memberId,
                });
                result.SetStatus(grpcResult);
                if (result.Success)
                {
                    result.Children = grpcResult.Response.Children.ToList();
                }
                return result;
            }
            else
            {
                result.Message = "用户ID不能为空";
            }
            return result;
        }

        public async Task<ChildCountResult> GetChildCount(List<long> memberIdList)
        {
            var result = new ChildCountResult();
            if (memberIdList.Count > 0)
            {
                var request = new GetChildCountRequest();
                request.MemberIdList.AddRange(memberIdList);
                var grpcResult = await RequestAsync(client.GetChildCountAsync, request);
                result.SetStatus(grpcResult);
                if (result.Success)
                {
                    result.CountList = grpcResult.Response.CountList.Select(c => new Results.ChildCountInfo()
                    {
                        ChildCount = c.ChildCount,
                        GroupCount = c.GroupCount,
                        MemberId = c.MemberId
                    }).ToList();
                }
                return result;
            }
            else
            {
                result.Message = "用户ID不能为空";
            }
            return result;
        }
    }
}
